package org.jeecg.modules.sxaq.anr.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.sxaq.anr.entity.RecordAbnormal;
import org.jeecg.modules.sxaq.anr.service.IRecordAbnormalService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
  * @Description: 异常记录
  * @Author DHC
  * @Date 2020-12-01
 */
@Api(tags="异常记录")
@RestController
@RequestMapping("/anr/recordAbnormal")
@Slf4j
public class RecordAbnormalController extends JeecgController<RecordAbnormal, IRecordAbnormalService> {
	@Autowired
	private IRecordAbnormalService recordAbnormalService;
	 @Autowired
	 private RedisUtil redisUtil;
	 @Autowired
	 private ISysUserService sysUserService;

	 @Value("${sxaq.redisUploadTime}")
	 private String redisUploadTime;
	 /**
	 * 分页列表查询
	 *
	 * @param recordAbnormal
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "异常记录-分页列表查询")
	@ApiOperation(value="异常记录-分页列表查询", notes="异常记录-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(RecordAbnormal recordAbnormal,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<RecordAbnormal> queryWrapper = QueryGenerator.initQueryWrapper(recordAbnormal, req.getParameterMap());
		Page<RecordAbnormal> page = new Page<RecordAbnormal>(pageNo, pageSize);
		IPage<RecordAbnormal> pageList = recordAbnormalService.page(page, queryWrapper);

		//批量查询用户的所属部门
		//step.1 先拿到全部的 useids
		//step.2 通过 useids，一次性查询用户的所属部门名字
		List<String> userIds = pageList.getRecords().stream().map(RecordAbnormal::getUserId).collect(Collectors.toList());
		if(userIds!=null && userIds.size()>0){
			Map<String,String>  useDepNames = sysUserService.getDepNamesByUserIds(userIds);
			pageList.getRecords().forEach(item->{
				item.setOrgCodeTxt(useDepNames.get(item.getUserId()));
			});
		}

		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param recordAbnormal
	 * @return
	 */
	@AutoLog(value = "异常记录-")
	@ApiOperation(value="异常记录-添加", notes="异常记录-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody RecordAbnormal recordAbnormal) {

		String userId = recordAbnormal.getUserId();
		if (userId == null || userId.isEmpty()) {
			return Result.error("用户id不能为空！");
		}

		recordAbnormalService.save(recordAbnormal);

		// 设置key time时间后失效
		// RedisKeyExpirationListener类监听这个key的值是否失效了
		// 如果失效了 说明在规定的时间内 没有上报数据 需要添加一条检测异常(服务器)数据
		// 如果规定的时间内上报了数据 这个key永远都不会失效

//		redisUtil.set(CommonConstant.SXAQ_NEXT_UPLOAD_TAG+"_"+userId, userId, Long.parseLong(redisUploadTime));

		return Result.OK("添加成功！");
	}

	 /**
	  *  批量添加
	  *
	  * @param records
	  * @return
	  */
	 @AutoLog(value = "异常记录-批量添加")
	 @ApiOperation(value="异常记录-批量添加", notes="异常记录-批量添加")
	 @PostMapping(value = "/addBatch")
	 public Result<?> addBatch(@RequestBody List<RecordAbnormal> records) {

		 if (records.size() == 0) {
			 return Result.error("上报数据不能为空！");
		 }
		 try {
			 this.recordAbnormalService.saveOrUpdateBatch(records);

			 // 设置key time时间后失效
			 // RedisKeyExpirationListener类监听这个key的值是否失效了
			 // 如果失效了 说明在规定的时间内 没有上报数据 需要添加一条检测异常(服务器)数据
			 // 如果规定的时间内上报了数据 这个key永远都不会失效

			 String userId = records.get(0).getUserId();
//			 redisUtil.set(CommonConstant.SXAQ_NEXT_UPLOAD_TAG+"_"+userId, userId, Long.parseLong(redisUploadTime));

			 return Result.OK("批量添加成功!");
		 } catch (Exception e) {
			 return Result.error("批量添加失败!");
		 }
	 }

	/**
	 *  编辑
	 *
	 * @param recordAbnormal
	 * @return
	 */
	@AutoLog(value = "异常记录-编辑")
//	@ApiOperation(value="异常记录-编辑", notes="异常记录-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody RecordAbnormal recordAbnormal) {
		recordAbnormalService.updateById(recordAbnormal);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "异常记录-通过id删除")
//	@ApiOperation(value="异常记录-通过id删除", notes="异常记录-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		recordAbnormalService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "异常记录-批量删除")
//	@ApiOperation(value="异常记录-批量删除", notes="异常记录-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.recordAbnormalService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "异常记录-通过id查询")
	@ApiOperation(value="异常记录-通过id查询", notes="异常记录-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		RecordAbnormal recordAbnormal = recordAbnormalService.getById(id);
		if(recordAbnormal==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(recordAbnormal);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param recordAbnormal
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, RecordAbnormal recordAbnormal) {
        return super.exportXls(request, recordAbnormal, RecordAbnormal.class, "异常记录");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	 public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		 return super.importExcel(request, response, RecordAbnormal.class);
	 }
}
